#!/bin/bash

# 数据库备份脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 配置变量
CONTAINER_NAME="git-env-dev"
BACKUP_DIR="backups"
DB_NAME="git_sync"
DB_USER="git_user"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_FILE="${BACKUP_DIR}/git_sync_backup_${TIMESTAMP}.sql"

echo -e "${BLUE}开始备份数据库...${NC}"

# 创建备份目录
mkdir -p $BACKUP_DIR

# 检查容器是否运行
if ! docker ps --format "{{.Names}}" | grep -q "^${CONTAINER_NAME}$"; then
    echo -e "${RED}错误: 容器 ${CONTAINER_NAME} 未运行${NC}"
    exit 1
fi

# 执行备份
echo -e "${BLUE}正在备份数据库 ${DB_NAME}...${NC}"
if docker exec "${CONTAINER_NAME}" pg_dump -h localhost -U "$DB_USER" -d "$DB_NAME" > "$BACKUP_FILE"; then
    echo -e "${GREEN}数据库备份成功!${NC}"
    echo -e "${GREEN}备份文件: ${BACKUP_FILE}${NC}"
else
    echo -e "${RED}数据库备份失败${NC}"
    exit 1
fi

# 压缩备份文件
echo -e "${BLUE}压缩备份文件...${NC}"
gzip "$BACKUP_FILE"
BACKUP_FILE_ZIPPED="${BACKUP_FILE}.gz"
echo -e "${GREEN}压缩完成: ${BACKUP_FILE_ZIPPED}${NC}"

# 显示备份文件大小
BACKUP_SIZE=$(du -h "$BACKUP_FILE_ZIPPED" | cut -f1)
echo -e "${GREEN}备份文件大小: ${BACKUP_SIZE}${NC}"

# 清理旧备份（保留最近7个）
echo -e "${BLUE}清理旧备份文件...${NC}"
cd $BACKUP_DIR
ls -t git_sync_backup_*.sql.gz | tail -n +8 | xargs -r rm -f
echo -e "${GREEN}旧备份清理完成${NC}"

# 恢复说明
echo -e "${BLUE}=== 恢复数据库说明 ===${NC}"
echo -e "${YELLOW}恢复命令: docker exec -i ${CONTAINER_NAME} psql -h localhost -U ${DB_USER} -d ${DB_NAME} < ${BACKUP_FILE_ZIPPED%.gz}${NC}"
echo -e "${YELLOW}注意: 恢复前需要先解压备份文件: gunzip ${BACKUP_FILE_ZIPPED}${NC}"

echo -e "${GREEN}数据库备份完成!${NC}"